package com.xsd.awen.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @author xxx
 * @date 2020-09-16 11:17
 **/

// mvn exec:java -Dexec.mainClass="com.xsd.awen.utils.AES256"

public class AES256 {
    private static final String ALGORITHM = "AES";
    private static final String KEY = "~dw8567@301&3#569pP01T3OokS8V012"; // 32 bytes key for AES-256

    // 加密方法
    public static String encrypt(String data){
        try {
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    // 解密方法
    public static String decrypt(String encryptedData){
        try {
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        try {
            // 待加密的数据
            String originalData = "116688";
            System.out.println("Original Data: " + originalData);

            // 加密数据
            String encryptedData = encrypt(originalData);
            System.out.println("Encrypted Data: " + encryptedData);

            // 解密数据
            String decryptedData = decrypt(encryptedData);
            System.out.println("Decrypted Data: " + decryptedData);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}